package com.city.helper;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.city.config.SMS;

/**
 * @author 雷楚桥
 * @deprecation 发送短信助手
 * @email leichuqiao@126.com
 * @date 2018/7/21 10:03
 */
public class SMSHelper {

    /**
     * @return boolean
     * @deprecation 发送短信
     * @params tel String 短信号码
     * @params code String 验证码
     * @author 雷楚桥
     * @date 2018/7/21 10:03
     */
    public static boolean send(String tel, String code) {

        //设置超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化
        final String product = SMS.PRODUCT;
        final String domain = SMS.DOMAIN;

        final String accessKeyId = SMS.ACCESS_KEY_ID;
        final String accessKeySecret = SMS.ACCESS_KEY_SECRET;

        //初始化ascClient
        IClientProfile profile = DefaultProfile.getProfile(SMS.REGION_ID, accessKeyId,
                accessKeySecret);
        try {
            DefaultProfile.addEndpoint(SMS.END_POINT_NAME, SMS.REGION_ID, product, domain);
        } catch (ClientException e) {
            e.printStackTrace();
        }

        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(SMS.SIGN_NAME);
        request.setTemplateCode(SMS.TEMPLATE_CODE);
        request.setMethod(MethodType.POST);


        request.setPhoneNumbers(tel);                                   //待发送手机号。
        request.setTemplateParam("{\"code\":\"" + code + "\"}");            //短信模板参数
        request.setOutId("yourOutId");                                  //拓展字段

        //请求失败
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            System.out.println("请求失败");
            e.printStackTrace();
        }

        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //请求成功
            System.out.println("send success , tel:" + tel);
            return true;
        } else {
            System.out.println("error code: " + sendSmsResponse.getCode());
        }
        return false;
    }

}
